package cn.conac.rc.gateway.modules.ofs.rest;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.gateway.modules.ofs.entity.DepartmentEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrgStatusEntity;
import cn.conac.rc.gateway.modules.ofs.service.DepartmentService;
import cn.conac.rc.gateway.modules.ofs.service.OrgStatusService;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value="ofs/")
@Api(tags="部门的内设机构", description="三定信息")
public class DepartmentController {

    @Autowired
    DepartmentService departmentService;
    
    @Autowired
    OrgStatusService  orgStatusService;
    
	@ApiOperation(value = "根据部门基本表ID取得内设机构列表信息", httpMethod = "GET", response = JSONObject.class, notes = "根据部门基本表ID取得内设机构列表信息")
    @RequestMapping(value = "bases/{baseId}/departments", method = RequestMethod.GET)
    public JSONObject findListById(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "部门基本表id", required = true) @PathVariable("baseId") String baseId)
            throws RestClientException, Exception {
        return departmentService.findListByBaseId(baseId);
    }
	
	@ApiOperation(value = "根据部门基本表ID取得带分层标示的内设机构列表信息", httpMethod = "GET", response = JSONObject.class, notes = "根据部门基本表ID取得带分层标示的内设机构列表信息（数据维护用）")
    @RequestMapping(value = "bases/{baseId}/level/flag/departments", method = RequestMethod.GET)
    public JSONObject findLevelFlagListById(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "部门基本表id", required = true) @PathVariable("baseId") String baseId)
            throws RestClientException, Exception {
        return departmentService.findLevelFlagListByBaseId(baseId);
    }
	
	
	@ApiOperation(value = "根据职能职责ID取得内设机构列表信息", httpMethod = "GET", response = JSONObject.class, notes = "根据职能职责ID取得内设机构列表信息")
    @RequestMapping(value = "dutys/{dutyId}/departments", method = RequestMethod.GET)
    public JSONObject findListByDutyId(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "职能职责ID", required = true) @PathVariable("dutyId") String dutyId)
            throws RestClientException, Exception {
        return departmentService.findListByDutyId(dutyId);
    }
	
	@ApiOperation(value = "根据baseId获取一级内设机构列表", httpMethod = "GET", response = JSONObject.class, notes = "根据baseId获取一级内设机构列表")
    @RequestMapping(value = "bases/{baseId}/levelOne/departments", method = RequestMethod.GET)
    public JSONObject findLevelOneByBaseId(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "职能职责ID", required = true) @PathVariable("baseId") String baseId)
            throws RestClientException, Exception {
        return departmentService.findLevelOneByBaseId(baseId);
    }
	
	@ApiOperation(value = "根据parentId获取内设机构列表", httpMethod = "GET", response = JSONObject.class, notes = "根据parentId获取内设机构列表")
    @RequestMapping(value = "departments/{parentId}", method = RequestMethod.GET)
    public JSONObject findByParentId(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "职能职责ID", required = true) @PathVariable("parentId") String parentId)
            throws RestClientException, Exception {
        return departmentService.findByParentId(parentId);
    }
	
	@ApiOperation(value = "根据baseId获取内设机构树", httpMethod = "GET", response = JSONObject.class, notes = "根据baseId获取内设机构树")
    @RequestMapping(value = "departments/mapTree/{baseId}", method = RequestMethod.GET)
    public JSONObject findMapTreeByBaseId(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "机构基本表ID", required = true) @PathVariable("baseId") String baseId)
            throws RestClientException, Exception {
        return departmentService.findMapTreeByBaseId(baseId);
    }
	
	@ApiOperation(value = "根据baseId获取包含机构名称的内设机构树", httpMethod = "GET", response = JSONObject.class, notes = "录入内设机构页面选择内设机构的上级机构用")
    @RequestMapping(value = "departments/deptTree/{baseId}", method = RequestMethod.GET)
    public JSONObject findDeptTreeByBaseId(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "机构基本表ID", required = true) @PathVariable("baseId") String baseId)
            throws RestClientException, Exception {
        return departmentService.findDeptTreeByBaseId(baseId);
    }
	
	@ApiOperation(value = "根据baseId获取内设机构列表", httpMethod = "GET", response = JSONObject.class, notes = "根据baseId获取内设机构列表")
    @RequestMapping(value = "departments/mapList/{baseId}", method = RequestMethod.GET)
    public JSONObject findMapListByBaseId(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "机构基本表ID", required = true) @PathVariable("baseId") String baseId)
            throws RestClientException, Exception {
        return departmentService.findMapListByBaseId(baseId);
    }
	
	@ApiOperation(value = "部门内设机构信息保存", httpMethod = "POST", response = JSONObject.class, notes = "部门内设机构信息保存")
    @RequestMapping(value = "departments/c", method = RequestMethod.POST)
    public Object cudDepartmentSave(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "部门内设机构信息和状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap  )
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 Map<String,String> idMap = new HashMap<String, String>();
    	 
    	 //******************第一步从页面侧获取部门内设机构信息和部门状态实体对象***********
         // 获得部门内设机构信息
    	 DepartmentEntity departmentEntityInfo = new DepartmentEntity();
    	 BeanMapper.copy(entityMap.get("deptEntity"), departmentEntityInfo);
    	
    	 // 确保部门内设机构信息中的ID不为null
    	 String baseId = departmentEntityInfo.getBaseId();
    	 if(null == baseId){
    		 //部门内设机构信息中的ID为null场合返回错误信息
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ the baseId of departmentEntityInfo is null] in function of departmentSave " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
   
         // 获得部门状态信息
         OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
         BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
       
         // 取得完整度掩码
         String stepMask = statusEntityInfo.getContentMask();
         // 判断是否是暂存[0]还是正常保存[1]，默认为正常保存 
         String submitType = "1";
         if(null  != stepMask ) {
        	 // 完整度掩码的格式为【111111】，当暂存场合 完整度掩码的第一个字符为[0],正常保存时为【1】
        	 submitType = stepMask.substring(3, 4);
         }
         
         //******************第二步保存部门内设机构信息表**************************************
         // 执行保存部门内设机构信息表
    	 JSONObject deptInfoJson =  departmentService.saveOrUpdate(submitType, departmentEntityInfo);
    	 
    	 // 判断保存是否成功失败
    	  if (ResultPojo.CODE_SUCCESS.equals(deptInfoJson.getString("code"))) {
    		  // 保存成功场合
    		  idMap.put("id", deptInfoJson.getJSONObject("result").getString("id"));
    		  idMap.put("baseId", deptInfoJson.getJSONObject("result").getString("baseId"));
    		  resultInfo.setResult(idMap);
          } else {
        	 // 保存失败场合
        	  resultInfo.setCode(deptInfoJson.getString("code"));
        	  resultInfo.setMsg("[dutyService.saveOrUpdate] in function of departmentSave " 
        			  					+ ResultPojo.MSG_FAILURE + "【"  + deptInfoJson.getString("msg") + "】");
        	  resultInfo.setResult(null);
         	  return resultInfo;
          }
    	  
    	 //*******************第三步保存部门的状态表******************************************
    	 // 设置状态表ID
    	 statusEntityInfo.setId(idMap.get("baseId"));
    	  // 设置登录用户ID
		 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.saveOrUpdate] in function of departmentSave " 
					  				+ ResultPojo.MSG_FAILURE + "【"  + statusInfoJson.getString("msg") + "】");
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // 删除保存的部门基本信息 TODO
			  return  resultInfo;
		  }
    	 
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }
    
    @ApiOperation(value = "部门内设机构信息更新", httpMethod = "POST", response = JSONObject.class, notes = "部门内设机构信息更新")
    @RequestMapping(value = "departments/{baseId}/u", method = RequestMethod.POST)
    public Object cudDepartmentUpdate(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam("部门基本信息Id") @PathVariable("baseId") String baseId,
            @ApiParam(value = "部门内设机构信息和状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap  )
            throws RestClientException, Exception {
    	
    	 ResultPojo resultInfo = new ResultPojo();
    	 if(null == baseId) {
    		  // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ baseId of parameter is null ] in function of departmentUpdate " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	 
    	 Map<String,String> idMap = new HashMap<String, String>();
    	 
    	 //******************第一步从页面侧获取部门内设机构信息和部门状态实体对象***********
         // 获得部门内设机构信息
    	 DepartmentEntity departmentEntityInfo = new DepartmentEntity();
    	 BeanMapper.copy(entityMap.get("deptEntity"), departmentEntityInfo);
    	 
    	 // 确保部门内设机构信息中的ID不为null
    	 if(null == departmentEntityInfo.getId()) {
    		 // 参数baseId为null场合
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ id of parameter is null ] in function of departmentUpdate " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
    	 }
    	// 确保部门内设机构信息中的baseID不为null
    	 departmentEntityInfo.setBaseId(baseId);
    	 
         // 获得部门状态信息
         OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
         BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
       
         // 取得完整度掩码
         String stepMask = statusEntityInfo.getContentMask();
         // 判断是否是暂存[0]还是正常保存[1]，默认为正常保存 
         String submitType = "1";
         if(null  != stepMask ) {
        	 // 完整度掩码的格式为【111111】，当暂存场合 完整度掩码的第一个字符为[0],正常保存时为【1】
        	 submitType =  stepMask.substring(3, 4);
         }
         
         //******************第二步保存部门内设机构信息表**************************************
         // 执行保存部门内设机构信息表
    	 JSONObject deptInfoJson =  departmentService.saveOrUpdate(submitType,departmentEntityInfo);
    	 
    	 // 判断保存是否成功失败
    	  if (ResultPojo.CODE_SUCCESS.equals(deptInfoJson.getString("code"))) {
    		  // 保存成功场合
    		  idMap.put("id", deptInfoJson.getJSONObject("result").getString("id"));
    		  idMap.put("baseId", deptInfoJson.getJSONObject("result").getString("baseId"));
    		  resultInfo.setResult(idMap);
          } else {
        	 // 保存失败场合
        	  resultInfo.setCode(deptInfoJson.getString("code"));
        	  resultInfo.setMsg("[dutyService.saveOrUpdate] in function of departmentUpdate " + 
        			  						ResultPojo.MSG_FAILURE + "【"  + deptInfoJson.getString("msg") + "】");
        	  resultInfo.setResult(null);
         	  return resultInfo;
          }
    	 
    	 //*******************第三步保存部门的状态表******************************************
    	 // 设置状态表ID
    	 statusEntityInfo.setId(idMap.get("baseId"));
    	  // 设置登录用户ID
		 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
		  // 执行保存部门的状态表
		  JSONObject statusInfoJson = orgStatusService.saveOrUpdate(statusEntityInfo);
		 
		  // 判断保存是否成功失败
		  if (ResultPojo.CODE_SUCCESS.equals(statusInfoJson.getString("code")) ) {
			  // 保存成功场合
			  resultInfo.setCode(ResultPojo.CODE_SUCCESS);
			  resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
		  } else {
			 // 保存失败场合
			  resultInfo.setCode(statusInfoJson.getString("code"));
			  resultInfo.setMsg("[orgStatusService.saveOrUpdate] in function of departmentUpdate " 
					  						+ ResultPojo.MSG_FAILURE + "【"   + statusInfoJson.getString("msg") + "】");
			  resultInfo.setResult(null);
		      // 程序事务控制
		  	  // 删除保存的部门基本信息 TODO
			  return  resultInfo;
		  }
    	 
         // 成功保存部门信息表和部门状态表返回
         return  resultInfo;
    }
    
	@ApiOperation(value = "根据内设机构id删除内设机构信息", httpMethod = "POST", response = JSONObject.class, notes = "根据内设机构id删除内设机构信息")
    @RequestMapping(value = "departments/{id}/d", method = RequestMethod.POST)
    public JSONObject  cudDepartmentDelete(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "删除对象id", required = true) @PathVariable(value = "id") String id)
            throws RestClientException, Exception {
        return departmentService.delete(id);
	}
	
	@ApiOperation(value = "根据内设机构id取得内设机构信息", httpMethod = "GET", response = JSONObject.class, notes = "根据内设机构id取得内设机构信息")
    @RequestMapping(value = "departments/{id}/r", method = RequestMethod.GET)
    public JSONObject departmentFindById(HttpServletRequest request, HttpServletResponse response,
    		@ApiParam(value = "对象id", required = true) @PathVariable(value = "id") String id)
            throws RestClientException, Exception {
		
        return departmentService.findById(id);
	}
	
    @ApiOperation(value = "向上移动内设机构", httpMethod = "POST", response = JSONObject.class, notes = "向上移动内设机构")
	@RequestMapping(value = "departments/move/up", method = RequestMethod.POST)
	 public JSONObject cudMoveUp(HttpServletRequest request, HttpServletResponse response,
	    		@ApiParam(value = "内设机构移动条件对象", required = true)  @RequestBody Map<String, Integer> condMap)
	            throws RestClientException, Exception {
	        return departmentService.moveUp(condMap);
	  }
    
    @ApiOperation(value = "向下移动内设机构", httpMethod = "POST", response = JSONObject.class, notes = "向下移动内设机构")
	@RequestMapping(value = "departments/move/down", method = RequestMethod.POST)
	 public JSONObject cudMoveDown(HttpServletRequest request, HttpServletResponse response,
	    		@ApiParam(value = "内设机构移动条件对象", required = true)  @RequestBody Map<String, Integer> condMap)
	            throws RestClientException, Exception {
	        return departmentService.moveDown(condMap);
	  }
}
